﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.ObjectMapping;
using WMS.Common;
using WMS.OutboundDetailss.Dto;
using WMS.RepositoryDefinitions;
using WMS.RepositoryDefinitions.Dto;

namespace WMS.OutboundDetailss
{
    public class OutboundDetailsService : ApplicationService, IOutboundDetailsService
    {
        private readonly IRepository<OutboundDetails, int> _repository;

        public OutboundDetailsService(IRepository<OutboundDetails, int> repository)
        {
            _repository = repository;
        }

        public async Task<int> AddOutboundDetails(OutboundDetailsDto outboundDetailsDto)
        {
            var detailsCode = _repository.AnyAsync(m => m.DetailsCode == outboundDetailsDto.DetailsCode).Result;
            if (detailsCode)
            {
                return -1;
            }

            var outboundDetailsModel = outboundDetailsDto.MapTo<OutboundDetails>();
            await _repository.InsertAsync(outboundDetailsModel);
            return outboundDetailsDto.Id;
        }

        public async Task<int> DeleteOutboundDetails(int id)
        {
            await _repository.DeleteAsync(id);
            return 1;
        }

        public async Task<OutboundDetailsDto> GetOutboundDetailsInfo(int id)
        {
            var entity = _repository.GetAsync(id).Result;
            var outboundDetailsDto = ObjectMapper.Map<OutboundDetails, OutboundDetailsDto>(entity);
            return outboundDetailsDto;
        }

        public async Task<PagedResult> GetOutboundDetailsList(string? detailsCode, int page = 1, int limit = 10)
        {
            var predicate = PredicateBuilder.New<OutboundDetails>(true);
            if (!string.IsNullOrEmpty(detailsCode))
            {
                predicate = predicate.And(m => m.DetailsCode.Contains(detailsCode));
            }
            var dto = _repository.GetListAsync(predicate).Result;
            PagedResult result = new PagedResult();
            result.PageCount = (int)Math.Ceiling((decimal)(dto.Count == 0 ? 1 : dto.Count) / limit);
            result.PageSize = limit;
            result.CurrentPage = page;
            result.RowCount = dto.Count;
            result.Queryable = dto.Skip((page - 1) * limit).Take(limit).AsQueryable();
            return result;
        }

        public async Task<int> UpdateOutboundDetails(OutboundDetailsDto outboundDetailsDto)
        {
            var detailsCode = await _repository.AnyAsync(m => m.DetailsCode == outboundDetailsDto.DetailsCode && m.Id != outboundDetailsDto.Id);

            OutboundDetails outboundDetails = outboundDetailsDto.MapTo<OutboundDetails>();
            await _repository.UpdateAsync(outboundDetails);
            return outboundDetails.Id;
        }
    }
}
